import java.util.Iterator;

public class HelperList<T> implements Iterable<T>{
	private Node head = null;
	private Node tail = null;
	
	protected class Node {
		T element;
		Node next = null;
		Node previous = null;
		
		Node(T element) {
			this.element = element;
		}
	}
	
	public void add(T element) {
		if(head == null) {
			head = tail = new Node(element);
		} else {
			Node currTail = tail;
			Node newTail = new Node(element);
			currTail.next = newTail;
			newTail.previous = currTail;
			tail = newTail;
		}
	}
	
	public void add(HelperList<T> elements) {
		if(elements == null) {
			return;
		}
		
		Node currentNode = elements.head;
		while(currentNode != null) {
			add(currentNode.element);
			currentNode = currentNode.next;
		}
	}
	
	protected Node getHead() {
		return head;
	}
	
	public Iterator<T> iterator() {
		return new ListIterator();
	}
	
	protected class ListIterator implements Iterator<T> {
		private Node current = getHead();
		private Node next = null;
		private Node previous = null;
		private boolean isFirst = true;
		
		protected ListIterator() {
			if(current != null) {
				next = current.next;
				previous = current.previous;
			}
		}
		
		private boolean endOfList = false;
		private boolean beginOfList = false;
		
		@Override
		public T next() {
			if(isFirst) {
				isFirst = false;
				return (current == null) ? null : current.element;
			}
			if(next == null) {
				endOfList = true;
				return null;
			}
			if(beginOfList) {
				beginOfList = false;
				return current.element;
			}
			current = next;
			previous = current.previous;
			next = current.next;
			return current.element;
		}

		public T previous() {
			if(isFirst) {
				isFirst = false;
				return (current == null) ? null : current.element;
			}
			if(previous == null) {
				beginOfList = true;
				return null;
			}
			if(endOfList) {
				endOfList = false;
				return current.element;
			}
			current = previous;
			previous = current.previous;
			next = current.next;
			return current.element;
		}

		@Override
		public boolean hasNext() {
			if(current == null) {
				return false;
			}
			if(isFirst) {
				return (current != null);
			}
			return (current.next != null);
		}

		public boolean hasPrevious() {
			if(current == null) {
				return false;
			}
			if(isFirst) {
				return (current != null);
			}
			return (current.previous != null);
		}

		@Override
		public void remove() {
			// TODO Auto-generated method stub
			
		}
	}
}
